package httplib;


import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

/**
 * The HTML Writer class receives data from a PUT HTTP request and writes it to a
 *  specified file
 * The HTML Writer is Thread safe. It will not let 2 threads write to the same file
 * @author dzgonjan
 *
 */
public class HtmlWriter extends HTMLFileHandler {
	
	//The name of the file this object represents
	private String fileName;
	private String responseString = "";
	
	/**
	 * The default constructor
	 * @param file - The name of the file to be written to
	 */
	public HtmlWriter(String file){
		this.fileName = file;
	}
	
	/**
	 * Write to the file.
	 * @param text - The text to be written to the file
	 */
	public String handleFile(String text){
		PrintWriter outputStream = null;
		
		try{
			outputStream = new PrintWriter(new FileWriter(fileName));
			outputStream.print(text);
			this.responseString = HTTPConstants.HTTPVersion + " " + HTTPConstants.OK_STATUS 
			+ " " + HTTPConstants.OK_STATUS_MSG + "\n" + HTTPConstants.RESPONSE_HEADER + text.length();
		
		} catch(Exception e){
			return HTTPConstants.FORBIDDEN_STATUS;
		} finally{
			if (outputStream != null){
				try{
					outputStream.close();
					
				} catch (Exception e) {
					return HTTPConstants.BAD_REQ_STATUS;
				}
			}
		}
		
		return HTTPConstants.OK_STATUS;
	}
	
	/**
	 * Returns the name of this file
	 * @return
	 */
	public String getFileName(){
		return this.fileName;
	}
	
	public String getResponseHeader(){
		return this.responseString;
	}
	
	public byte[] getResponseFile(){
		byte[] ret = null;
		try{
			ret =  this.getBytesFromFile(new File(this.fileName));
		} catch(Exception e){
			System.out.println(e.getMessage());
		}
		return ret;
	}
}

